package org.quartz.ui.web.action.interceptors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Scheduler;
import org.quartz.ui.web.action.schedule.ScheduleBase;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * @author zhurx4g@gmail.com
 */
public class SchedulerCheckInterceptor implements Interceptor {

	/**
     * 
     */
	private static final long serialVersionUID = 7866830754878384779L;
	private static final Log logger = LogFactory
			.getLog(SchedulerCheckInterceptor.class);
	private static final String DEFAULT_FAIL_RESULT = "error";

	String failResult = DEFAULT_FAIL_RESULT;

	public String getFailResult() {
		return failResult;
	}

	public void setFailResult(String failResult) {
		this.failResult = failResult;
	}

	public void destroy() {

	}

	public void init() {
	}

	public String intercept(ActionInvocation invocation) throws Exception {

		String actionName = invocation.getInvocationContext().getName();
		Scheduler scheduler = ScheduleBase.getCurrentScheduler();
		if (!scheduler.isInStandbyMode() || !scheduler.isShutdown()) {

			return invocation.invoke();
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("Scheduler not running or is down will not attempt to execute:"
								+ actionName);
			}

			return failResult;
		}

	}

}
